<template>
  <div class="search">
    <!-- 搜索框 -->
    <div
      class="searchTxtb"
      :id="barShow ? 'Txtb-show' : 'Txtb'"
      @click="searchTxtbShowControll"
    >
      <!-- 输入框 -->
      <input
        type="text"
        v-model="inputValue"
        placeholder="请输入地址名或道路名"
        v-show="barShow"
        @keyup.enter="searchRun"
        ref="myInput"
      />
      <loading v-if="isLoading" />
      <!-- 搜索按钮 -->
      <div class="button">
        <div @click="searchRun" class="searchRun">
          <div class="buttonMask"></div>
          <span>全要素搜索</span>
        </div>
      </div>
    </div>
    <!-- 下拉框 -->
    <transition name="fade">
      <div
        class="dropDown"
        :style="{ padding: searchResult.length > 0 ? '1%' : '0' }"
        v-show="dropDownShow"
      >
        <!-- 搜索结果 -->
        <div
          class="dropDownPart"
          v-for="(resultList, index) in searchResult"
          :key="index"
          :style="{ 'max-height': `${innerHeight}px` }"
        >
          <el-collapse
            v-model="collapseRef"
            v-for="(result, index1) in resultList"
            :key="index1"
          >
            <el-collapse-item :name="result.index">
              <template #title>
                <div class="resultTitle">
                  <img
                    :src="
                      require('@/assets/images/icon/selectResult/' +
                        result.data.type +
                        '.png')
                    "
                  />
                  <span>{{ result.data.type }}</span>
                  <span class="resultLength">{{ result.data.length }}条</span>
                </div>
                <info-filled />
              </template>
              <div
                class="searchResultContainer"
                :id="'searchResultContainer' + index"
              >
                <div
                  class="searchResult"
                  v-for="(data, index2) in result.data.arr"
                  :key="index2"
                  @click="toAddress(data)"
                >
                  <div class="searchResultBG"></div>
                  <div class="result">
                    <span>{{ data.name }}</span>
                    <div class="tagList">
                      <div
                        class="tag"
                        v-for="(tag, index) in data.tagList"
                        :key="index"
                        :style="{ backgroundColor: tag.color }"
                      >
                        {{ tag.text }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
/* eslint-disable */
import { getCurrentInstance, onMounted, ref } from "vue";
import pubsub from "pubsub-js";
import axios from "axios";

import urlList from "@/store/urlList.json";
import Message from "@/components/Message/showMessage";
import loading from "@/components/Loading/loading.vue";

import mapApi from "@/api/mapApi.js";
import normalApi from "@/api/normalApi.js";
import enterprise_colorList from "@/json/enterprise_colorList.json";

export default {
  components: { loading },
  name: "工具栏",
  components: {
    loading,
  },
  data() {
    return {
      dropDownShow: true,
      barShow: false,
      subList: [],
      searchResultShow: true,
      inputValue: "中铁",
      searchResultLength: 0,
      searchResult: [],
      clearMapButtonStyle: "unClear",
      isLoading: false,
      innerHeight: window.innerHeight * 0.85,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    let collapseRef = ref([]);

    // url列表
    // let urlList;
    // normalApi.getUrlList().then((res) => {
    //   urlList = res.urlList;
    // });

    onMounted(() => {
      document.documentElement.style.setProperty(
        "--maxHeight",
        `${proxy.innerHeight * 0.95}px`
      );
      setTimeout(() => {
        proxy.barShow = true;
      }, 1000);
      subscribeList();
    });

    // pubsub列表
    function subscribeList() {
      proxy.subList.push(
        // 组件显隐
        pubsub.subscribe("searchShowControll", (n, data) => {
          proxy.barShow = data;
        }),
        // 下拉框显隐
        pubsub.subscribe("dropDownShowControll", (n, data) => {
          proxy.dropDownShow = data;
        })
      );
    }

    // 执行搜索
    function searchRun() {
      // 空值预警
      if (proxy.inputValue === "") {
        Message("请勿输入空值", "error");
        return;
      }
      // 开启查询样式
      proxy.isLoading = true;
      // 输入值
      let value = proxy.inputValue;
      // 查询列表
      let requestList = [
        searchCouryYard(value),
        searchEnterprise(value),
        searchRoad(value),
        searchNaturalResource(value),
        searchAddress(value),
      ];
      // 读取查询结果
      Promise.all(requestList).then((res) => {
        // 去除查询失败的类型
        res = res.filter((item) => item !== undefined);
        console.log(res);
        // 结果长度
        proxy.searchResultLength = 0;
        res.forEach((element) => {
          proxy.searchResultLength += element.arr.length;
        });
        // 结果长度显示
        Message(`查询成功,共查询到${proxy.searchResultLength}条记录`);
        // 下拉显示
        pubsub.publish("dropDownShowControll", true);
        // 结果载入
        proxy.searchResult = [];
        let tempArr = res.pop();
        for (let index = 0; index < res.length; index += 2) {
          let arr = [];
          res[index] != undefined &&
            arr.push({
              index,
              data: res[index],
            });
          res[index + 1] != undefined &&
            arr.push({
              index: index + 1,
              data: res[index + 1],
            });
          proxy.searchResult.push(arr);
        }
        proxy.searchResult.unshift([{ index: 0, data: tempArr }]);
        console.log(proxy.searchResult);
        // 展开
        setTimeout(() => {
          for (let index = 0; index < requestList.length; index++) {
            collapseRef.value.push(index);
          }
          proxy.isLoading = false;
        }, 300);
      });
    }

    // 地址搜索
    function searchAddress(address_name) {
      //发送请求
      return axios({
        method: "get",
        url: urlList.addressMatchURL_136,
        params: {
          address: address_name,
          fromIndex: "0",
          toIndex: "999",
          maxReturn: -1,
        },
      })
        .then((res) => {
          // 空值提醒
          if (res.data.length === 0) {
            Message("无查询结果,请重试", "error");
          }
          // 储值数组
          let arr = [];
          // 填入搜索结果
          res.data.forEach((element) => {
            arr.push({
              name: element.address,
              address: element.location,
            });
          });
          // 返回
          return new Promise((res, rej) => {
            res({
              type: "地址",
              arr,
              length: arr.length,
            });
          });
        })
        .catch((error) => {
          Message(`地址查询：服务器错误${error}`, "error", 5000);
        });
    }

    // 搜索道路
    function searchRoad(address_name) {
      // 生成请求列表
      let requestList = requestGenerator(address_name);
      // 执行请求
      return Promise.all(requestList)
        .then((responses) => {
          let resultList = responses[0].data.features;
          // console.log(resultList);
          // 空值提醒
          if (resultList.length === 0) {
            Message("无查询结果,请重试", "error");
          }
          // 储值数组
          let arr = [];
          // 请求结果数据处理
          resultList.forEach((feature) => {
            // 填入搜索结果
            arr.push({
              // id: feature.attributes["FID"],
              name: feature.attributes["NAME"],
              paths: feature.geometry.paths,
              center: {
                lat: feature.attributes.centerY,
                lng: feature.attributes.centerX,
              },
              length:
                feature.attributes.Length || feature.attributes.Shape_Length,
            });
          });
          // 返回
          return new Promise((res, rej) => {
            res({
              type: "道路",
              arr,
              length: arr.length,
            });
          });
        })
        .catch((error) => {
          console.log(error);
          Message(`道路查询：服务器错误${error}`, "error");
        });
    }

    // 搜索自然资源
    function searchNaturalResource(address_name) {
      //发送请求
      return axios({
        method: "get",
        url: urlList.naturalResourceURL,
        params: {
          where: "NAME LIKE '%" + address_name + "%'",
          geometryType: "esriGeometryEnvelope",
          mapExtent: "45330.913495,171563.757422,80595.887643,203928.9151",
          imageDisplay: "60055096",
          f: "json",
          outFields: "*",
        },
      })
        .then((res) => {
          // console.log(res.data);
          // 空值提醒
          if (res.data.length === 0) {
            Message("无查询结果,请重试", "error");
          }
          // 储值数组
          let arr = [];
          // 填入搜索结果
          res.data.features.forEach((feature) => {
            // console.log(feature);
            arr.push({
              name: feature.attributes.Name,
              rings: feature.geometry.rings,
              center: {
                lat: feature.attributes.centerY,
                lng: feature.attributes.centerX,
              },
              length:
                feature.attributes.Length || feature.attributes.Shape_Length,
            });
          });
          // 返回
          return new Promise((res, rej) => {
            res({
              type: "自然资源",
              arr,
              length: arr.length,
            });
          });
        })
        .catch((error) => {
          Message(`自然资源查询：服务器错误${error}`, "error");
        });
    }

    // 搜索院落
    function searchCouryYard(address_name) {
      //发送请求
      return axios({
        method: "get",
        url: urlList.courtYardURL,
        params: {
          where: "NAME LIKE '%" + address_name + "%'",
          geometryType: "esriGeometryEnvelope",
          mapExtent: "45330.913495,171563.757422,80595.887643,203928.9151",
          imageDisplay: "60055096",
          f: "json",
          outFields: "*",
        },
      })
        .then((res) => {
          // console.log(res.data);
          // 空值提醒
          if (res.data.length === 0) {
            Message("无查询结果,请重试", "error");
          }
          // 储值数组
          let arr = [];
          // 填入搜索结果
          res.data.features.forEach((feature) => {
            // console.log(feature);
            arr.push({
              name: feature.attributes.Name,
              rings: feature.geometry.rings,
              center: {
                lat: feature.attributes.centerY,
                lng: feature.attributes.centerX,
              },
              length: 0,
            });
          });
          // 返回
          return new Promise((res, rej) => {
            res({
              type: "院落",
              arr,
              length: arr.length,
            });
          });
        })
        .catch((error) => {
          Message(`院落查询：服务器错误${error}`, "error");
        });
    }

    // 搜索企业
    function searchEnterprise(address_name) {
      //发送请求
      return axios({
        method: "get",
        url: urlList.enterpriseURL,
        params: {
          where: "qymc LIKE '%" + address_name + "%'",
          geometryType: "esriGeometryEnvelope",
          mapExtent: "45330.913495,171563.757422,80595.887643,203928.9151",
          imageDisplay: "60055096",
          f: "json",
          outFields: "*",
        },
      })
        .then((res) => {
          // console.log(res.data.features);
          // 空值提醒
          if (res.data.length === 0) {
            Message("无查询结果,请重试", "error");
          }
          // 储值数组
          let arr = [];
          // 填入搜索结果
          res.data.features.forEach((feature) => {
            // 标签填入
            let tagList = [];
            feature.attributes["qybq"].split(";").forEach((tag) => {
              for (const key in enterprise_colorList) {
                if (Object.hasOwnProperty.call(enterprise_colorList, key)) {
                  const color = enterprise_colorList[key];
                  // 键名匹配颜色
                  if (key === tag) {
                    tagList.push({
                      text: tag.substring(0, 1),
                      color,
                    });
                  }
                }
              }
            });
            // 信息填入
            arr.push({
              name: feature.attributes.qymc,
              data: feature.attributes,
              center: {
                lat: feature.attributes.centerY,
                lng: feature.attributes.centerX,
              },
              tagList,
              length: 0,
            });
          });
          // 返回
          return new Promise((res, rej) => {
            res({
              type: "企业",
              arr,
              length: arr.length,
            });
          });
        })
        .catch((error) => {
          Message(`企业查询：服务器错误${error}`, "error");
        });
    }

    // 请求生成器
    function requestGenerator(road_address) {
      // 请求列表
      let requstList = [];
      [urlList.roadUrl].forEach((url) => {
        requstList.push(
          axios({
            method: "get",
            url,
            params: {
              where: "NAME LIKE '%" + road_address + "%'",
              geometryType: "esriGeometryEnvelope",
              mapExtent: "45330.913495,171563.757422,80595.887643,203928.9151",
              imageDisplay: "60055096",
              f: "json",
              outFields: "*",
            },
          })
        );
      });
      return requstList;
    }

    // 地址跳转
    function toAddress(address) {
      // 传输至地图
      if (address.rings) {
        // 面要素
        pubsub.publish("toPolygonAddress", address);
      } else if (address.paths) {
        // 线要素
        pubsub.publish("toPolylineAddress", address);
      } else {
        // 点要素
        // 企业详细数据整理
        // if (address.data) {
        //   address.data = mapApi.enterpriseDataHandle(address.data);
        // }
        // console.log(address, address.data);
        // 数据发送
        pubsub.publish("toPointAddress", address);
      }
    }

    // 输入框控制下拉框显隐
    function searchTxtbShowControll() {
      pubsub.publish("dropDownShowControll", true);
      pubsub.publish("spatialQueryShowControll", false);
    }

    return {
      searchRun,
      toAddress,
      collapseRef,
      searchTxtbShowControll,
    };
  },
  watch: {
    isLoading(newValue) {
      if (newValue) {
        this.$refs.myInput.focus();
      } else {
        this.$refs.myInput.blur();
      }
    },
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
* {
  border-radius: 5px !important;
}

.search {
  box-shadow: 2px 2px 2px 0px rgba(0, 0, 0, 0.1);
}

.searchTxtb {
  background-color: white;
  height: 35px;
  z-index: 9999;
  border-radius: 5px;
  overflow: hidden;
  transition: width 0.5s ease;
  display: flex;
  align-items: center;
  position: relative;
  > input {
    width: 73%;
    height: 80%;
    padding: 0 5px;
    border-radius: 5px;
    margin-left: 1%;
    border: white 1px solid;
  }

  > input:focus,
  input:hover {
    border: #3f69e4 1px solid;
  }

  > .button {
    width: 24%;
    height: 80%;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 1%;
    > div {
      width: 100%;
      height: 100%;
      min-width: 50px;
      border-radius: 5px;
      font-family: "黑体";
      font-size: 110%;
      color: #3f69e4;
      transition: color 0.3s ease;
      display: flex;
      justify-content: center;
      align-items: center;
      > .buttonMask {
        position: absolute;
        z-index: 0;
        background-color: #3f69e4;
        top: 0%;
        left: 0%;
        width: 0%;
        height: 100%;
        transition: width 0.3s ease;
      }
      > span {
        position: absolute;
        z-index: 999;
        display: inline-block;
        background-color: transparent;
      }
    }
    > div:hover {
      color: white;
      cursor: pointer;
    }
  }
}

.searchRun:hover > .buttonMask {
  width: 100% !important;
}

#Txtb {
  width: 0px;
}

#Txtb-show {
  width: 500px;
}

.dropDown {
  border: #3f69e4 1px solid;
  background-color: white;
  border-radius: 5px;
  position: absolute;
  z-index: 99999;
  top: 100%;
  transition: height 0.5s ease;
  display: flex;
  flex-direction: row;
  > .dropDownPart {
    // max-height: 1100px;
    overflow: hidden;
  }
}

.el-collapse {
  width: 500px;
}

.searchResultContainer {
  max-height: 550px;
  overflow-y: auto;
  overflow-x: hidden;
}

#searchResultContainer0 {
  max-height: var(--maxHeight);
}

.searchResultContainer::-webkit-scrollbar {
  width: 1px;
}

.searchResultContainer::-webkit-scrollbar-thumb {
  height: 25px;
  border-radius: 10px;
  background: #3f69e4;
}

.searchResultContainer::-webkit-scrollbar-track {
  background: transparent;
}

.resultTitle {
  display: flex;
  align-items: center;
  width: 100%;
  font-family: "黑体";
  color: #3f69e4;
  font-size: 100%;
  font-weight: bold;
  > * {
    margin: 0 0.5%;
  }
  > img {
    width: 20px;
  }
  > .resultLength {
    color: #000;
    font-weight: normal;
    font-size: 80%;
  }
}

.searchResult {
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: black;
  border-radius: 5px;
  position: relative;
  font-weight: normal;
  transition: font-weight 0.3s ease;
  > .result {
    // display: inline-block;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: transparent;
    position: absolute;
    z-index: 999;
    > .tagList {
      display: flex;
      flex-direction: row;
      color: white !important;
      font-weight: normal !important;
      > .tag {
        padding: 0 5px;
        margin: 0 3px;
      }
    }
  }
  > .searchResultBG {
    background-color: rgb(249, 249, 249);
    width: 0px;
    height: 35px;
    position: absolute;
    z-index: 0;
    transition: width 0.3s ease;
  }
}

.searchResult:hover {
  color: #3f69e4;
  font-weight: bold;
  cursor: pointer;
}

.searchResult:hover > .searchResultBG {
  width: 500px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>